package org.mayanjun.code.easyweb.springmvc.io;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;

/**
 * 
 * @author mayanjun
 */
public final class BeanSerializer {
	private BeanSerializer() {}
	
	/**
	 * 
	 * @param requestBean
	 * @return
	 * @author mayanjun
	 * @since 1.0.1
	 */
	public static String serializeToXMLFragment(Object requestBean) {
		ByteArrayOutputStream out = null;
		try {
			JAXBContext ctx = JAXBContext.newInstance(requestBean.getClass());
			Marshaller mar = ctx.createMarshaller();
			mar.setProperty(Marshaller.JAXB_FRAGMENT, true);
			mar.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
			out = new ByteArrayOutputStream();
			mar.marshal(requestBean, out);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		return new String(out.toByteArray());
	}
	
	@SuppressWarnings({ "unchecked" })
	public static <T> T unserializeFromXML(String xml, Class<T> clazz) {
		ByteArrayInputStream in = null;
		T obj = null;
		try {
			JAXBContext context = JAXBContext.newInstance(clazz);
	        Unmarshaller unmarshaller = context.createUnmarshaller();
	        in = new ByteArrayInputStream(xml.getBytes());
	        obj = (T) unmarshaller.unmarshal(in);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return obj;
	}
	
	
	@SuppressWarnings("unchecked")
	public static <T> T unserializeFromXML(File file, Class<T> clazz) {
		T obj = null;
		try {
			JAXBContext context = JAXBContext.newInstance(clazz);
	        Unmarshaller unmarshaller = context.createUnmarshaller();
	        obj = (T) unmarshaller.unmarshal(file);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return obj;
	}
}
